<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Parts as PartsModel;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\PartsStock;
use addons\qingdongams\model\PartsStockReload;
use think\Db;
use think\Exception;


/**
 * 零件管理
 */
class Parts extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];


    //获取零件列表
    public function getList()
    {
        $limit = input("limit/d", 10);
        $params = $this->request->post();
        $where = [];
        $stock='';
        $order = 'id desc';
        if (isset($params['name']) && $params['name']) {//产品名称
            $where['name'] = ['like', "%{$params['name']}%"];
        }
        if(isset($params['type']) && $params['type'] == 1){
         $stock='stock <= warning_stock';
        }
        $list = PartsModel::where($where)->with([
            'createStaff',
        ])->where($stock)->order($order)->paginate($limit);
        $this->success('请求成功', $list);
    }


    //获取selelct列表
    public function getSelectList()
    {
        $name = input('name');
        $product_id = input('product_id');
        $where = [];
        if ($name) {
            $where['name'] = ['like', "%{$name}%"];
        }
        $whereProduct = [];
        if ($product_id) {//产品
            $product_id=intval($product_id);
            $whereProduct[] = ['exp', Db::raw('FIND_IN_SET(' . $product_id . ',product_id)')];
        }
        $list = PartsModel::where($where)
            ->where($whereProduct)
            ->with(['createStaff'])
            ->field('id,name,stock,num,img,unit,price,status')->select();
        $this->success('请求成功', $list);
    }


    //添加零件
    public function addParts()
    {
        $params = $this->request->post();

        if (PartsModel::where(['name' => $params['name']])->find()) {
            $this->error('零件名称已存在');
        }

        try {
            $result = PartsModel::createParts($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('新增零件成功');
        }
    }


    //修改零件
    public function editParts()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = PartsModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('修改零件信息不存在');
        }
        $params['product_id']=implode(',',$params['product_id']);
        // 表单验证
        if (($result = $this->qingdongamsValidate($params,get_class(), 'edit')) !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $result = PartsModel::updateParts($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改零件信息成功');
    }


    //获取零件详情
    public function getPartsDetail()
    {
        $id = input('id');
        $parts = PartsModel::where(['id' => $id])->with(['createStaff'])->find();
        if (empty($parts)) {
            $this->error('零件信息不存在');
        }
        if (!empty($parts['product_id'])) {
            $product_ids = explode(',', $parts['product_id']);
            $names = \addons\qingdongams\model\Product::where(['id' => ['in', $product_ids]])->column('name');
            $parts['product_name'] = implode(',', $names);
        }
        $parts['stocks'] = PartsStock::where(['parts_id' => $id])->with(['createStaff'])->select();

        Message::setRead(Message::PARTS_TYPE,$id,$this->auth->id);
        $this->success('请求成功', $parts);
    }


    //获取库存记录
    public function getStockRecord()
    {
        $parts_id = input('parts_id');
        $type = input('type');
        if (empty($parts_id)) {
            $this->error('库存不存在');
        }
        $where = ['parts_id' => $parts_id];
        if ($type) {
            $where['type'] = $type;
        }
        $stocks = PartsStock::where($where)->with(['parts', 'createStaff'])->select();

        $this->success('请求成功', $stocks);
    }


    //添加库存
    public function addStocks()
    {
        $params = $this->request->post();
        // 表单验证
        if (($result = $this->validate($params, 'addons\qingdongams\validate\PartsStockReload.create')) !== true) {
            $this->error($result);
        }

        Db::startTrans();
        try {
            $parts = [];
            foreach ($params['parts'] as $part) {
                $parts[] = ['id' => $part['id'], 'number' => $part['number']];
            }
            $params['parts'] = json_encode($params['parts']);

            PartsStockReload::addRecord($params);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('提交成功');
    }

    //首页-库存审批记录
    public function examineStockRecord()
    {
        $limit = input('limit', 10);
        $type = input('type');//1 出库 入库
        $check_status = input('check_status'); //审核状态 1审核中、2审核通过、3审核未通过
        $where = [];
        if ($type) {
            $where['type'] = $type;
        }
        $whereFlow = [];
        $where = [];


        if ($check_status) {
            //0待审核、1审核中、2审核通过、3审核未通过、4撤销
            if ($check_status == 1) {
                $where['check_status'] = ['in', [0, 1]];
            } elseif ($check_status == 2) {
                $where['check_status'] = 2;
            } elseif ($check_status == 3) {
                $where['check_status'] = ['in', [3, 4]];
            }
        }
        $select = PartsStockReload::where($where)->with(['createStaff'])->paginate($limit);

        $this->success('请求成功', $select);
    }

    //我的库存记录
    public function myStockRecord()
    {
        $limit = input('limit', 10);
        $times = input('times');
        $type = input('type');//
        $check_status = input('check_status');//审核状态 1审核中、2审核通过、3审核未通过
        $check_type = input('check_type', 1);

        $where = [];
        $whereFlow = [];
        if ($type) {
            $where['type'] = $type;
        }
        if ($check_type == 1) {//我发起的
            $where['create_staff_id'] = $this->auth->id;
        } elseif ($check_type == 2) {//我审批的
            $whereFlow[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',flow_staff_ids)')];
        }
        if ($check_status) {
            //0待审核、1审核中、2审核通过、3审核未通过、4撤销
            if ($check_status == 1) {
                $where['check_status'] = ['in', [0, 1]];
            } elseif ($check_status == 2) {
                $where['check_status'] = 2;
            } elseif ($check_status == 3) {
                $where['check_status'] = ['in', [3, 4]];
            }
        }
//        $where['create_staff_id'] = $this->auth->id;
        if ($times) {//创建时间
            $times = explode(',', $times);
            $where['createtime'] = ['between', [$times[0], $times[1]]];
        }
        $select = PartsStockReload::where($where)->where($whereFlow)->order('id desc')->with(['createStaff'])->paginate($limit);

        $this->success('请求成功', $select);
    }

    //获取我的 已申请和待我审核
    public function getReloadNumber()
    {
        $check_type = input('check_type', 1);

        $where = [
            'check_status' => ['in', [0, 1]],];
        $whereFlow = [];

        if ($check_type == 1) {//我发起的
            $where['create_staff_id'] = $this->auth->id;
        } elseif ($check_type == 2) {//我审批的
            $whereFlow[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',flow_staff_ids)')];
        }

        $ruku = PartsStockReload::where([
            'type' => 1,
        ])->where($where)->where($whereFlow)->count();
        $chuku = PartsStockReload::where([
            'type' => 2,
        ])->where($where)->where($whereFlow)->count();


        $this->success('请求成功', ['ruku' => $ruku, 'chuku' => $chuku]);
    }

    //获取零件审批详情
    public function getPartsReloadDetail(){
        $id=input('id');
        $detail = PartsStockReload::where([
            'id' => $id,
        ])->with(['createStaff'])->find();
        $detail['is_examine'] = 0;
        $detail['is_operation'] = 0;
        if(in_array($detail['check_status'],[0,1]) && in_array($this->auth->id,explode(',',$detail['flow_staff_ids']))){
            $detail['is_examine'] = 1;
            $detail['is_operation'] = 1;
        }
        if($detail['create_staff_id'] == $this->auth->id){
            //是否可以操作
            $detail['is_operation']=1;
        }
        Message::setRead(Message::PARTS_TYPE,$id,$this->auth->id);
        $this->success('请求成功', $detail);
    }

    //获取零件编号
    public function getPartsNumber()
    {
        $this->success('请求成功', ['number' => 'KQ' . date('Ymdhis') . rand(1000, 9999)]);
    }


}
